package jys.test.yddata;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;

import java.io.IOException;

import jys.test.yddata.ui.ToolbarPlus;
import jys.test.yddata.utils.PropertiesUtil;
import jys.test.yddata.utils.VerifyManager;

public class SettingsActivity extends AppCompatActivity {
    private ToolbarPlus mToolbar;
    private VerifyManager verifyManager;
    private PropertiesUtil projectProp, serverProp;
    private View loadingView, okView, noView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        mToolbar = findViewById(R.id.settingBar);
        loadingView = findViewById(R.id.loading);
        okView = findViewById(R.id.ok);
        noView = findViewById(R.id.no);

        try {
            projectProp = PropertiesUtil.buildFromDisk(this, "project");
            serverProp = PropertiesUtil.buildFromDisk(this, "server");
        } catch (IOException e) {
            e.printStackTrace();
            seriousError("配置加载出错，Exp ["+e.getMessage()+"]");
        }

        try { initView(); } catch (Exception e) {
            e.printStackTrace();
            seriousError("视图加载出错，Exp ["+e.getMessage()+"]");
        }

        // 加载服务器配置及发送功能
        verifyManager = new VerifyManager.Builder()
                .init(this,
                        this::endLoading_Verify,
                        serverProp.getProperty("verify.url"))
                .build();
    }

    public void initView() {
        // 加载 Toolbar
        mToolbar.settingLeft(R.drawable.ic_left_arrow, (v)->finish())
                .settingTitle("设置")
                .settingRight(R.drawable.ic_save, this::jump2MainWithSave);
        setSupportActionBar(mToolbar);

        Switch onT9 = findViewById(R.id.onT9);
        onT9.setChecked(projectProp.getBooleanProperty("view.showT9"));

        Switch onLevel = findViewById(R.id.onLevel);
        onLevel.setChecked(projectProp.getBooleanProperty("view.showLevel"));
    }

    public void jump2MainWithSave(View v) {
        Switch onT9 = findViewById(R.id.onT9);
        Switch onLevel = findViewById(R.id.onLevel);
        projectProp.setProperty("view.showT9", String.valueOf(onT9.isChecked()));
        projectProp.setProperty("view.showLevel", String.valueOf(onLevel.isChecked()));
        try { projectProp.storeToUser(); } catch (IOException e) {
            e.printStackTrace();
            seriousError("配置保存出错，Exp ["+e.getMessage()+"]");
        }
        finish();
    }

    public void jump2Document(View v) {
        if(!isNetworkConnected())
            new AlertDialog.Builder(this)
                    .setTitle("错误")
                    .setMessage("网络未连接，无法访问")
                    .setPositiveButton("确认", (dialog, which)->{})
                    .show();
        else {
            Intent intent = new Intent(this, DocumentActivity.class);
            startActivity(intent);
        }
    }

    public void jump2Verify(View v) {
        if(!isNetworkConnected())
            new AlertDialog.Builder(this)
                    .setTitle("错误")
                    .setMessage("网络未连接，无法更换")
                    .setPositiveButton("确认", (dialog, which)->{})
                    .show();
        else {
            final EditText verifyView = new EditText(this);
            verifyView.setHint("此处填写数据集校验码");
            verifyView.setPadding(0, 50, 0, 50);
            verifyView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            new AlertDialog.Builder(this)
                    .setTitle("数据集更新")
                    .setView(verifyView)
                    .setPositiveButton("确认", (dialog, which)->{
                        startLoading();
                        String verify = verifyView.getText().toString();
                        verifyManager.sendVerify(verify);
                    })
                    .setNegativeButton("取消", (dialog, which)->{})
                    .show();
        }
    }

    public boolean startLoading() {
        loadingView.setVisibility(View.VISIBLE);
        return true;
    }

    public void endLoading_Verify(boolean isOK) {
        loadingView.setVisibility(View.GONE);
        if (isOK) okView.setVisibility(View.VISIBLE);
        else noView.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, MainActivity.class);
        this.startActivity(intent);
        System.exit(0);
        this.finish();
    }

    /**
     * 判断网络状态
     */
    private boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null)
            return mNetworkInfo.isAvailable();
        return false;
    }

    public void seriousError(String message) {
        new AlertDialog.Builder(this)
                .setTitle("错误")
                .setMessage(message)
                .setPositiveButton("退出", (dialog, which)-> finish())
                .show();
    }
}
